"use client"
import { Mainbar } from "@/components/NavBar/mainBar";
import { fetchWithAuth } from "@/request/request";
import { useRouter } from "@/utils/router";
import { useState, useEffect, useRef } from "react";
import { BarChart, Bar, XAxis, YAxis, Tooltip, Legend, ResponsiveContainer } from "recharts";

// 定义数据类型
interface StudyEntry {
    date: string;
    title: string;
    duration: number;
}

interface TransformedEntry {
    date: string;
    [key: string]: string | number;
}

export default function My() {

    const router = useRouter();
    const { currentPath } = router
    const [studyTime, setStudyTime] = useState<TransformedEntry[]>([]);

    const ti: StudyEntry[] = [
        { "date": "2025-03-14", "title": "Node.js Handbook", "duration": 60 },
        { "date": "2025-03-14", "title": "JavaScript Basics", "duration": 20 },
        { "date": "2025-03-17", "title": "JavaScript Basics", "duration": 50 },
        { "date": "2025-03-18", "title": "JavaScript Basics", "duration": 50 },
        { "date": "2025-03-19", "title": "JavaScript Basics", "duration": 50 },
        { "date": "2025-03-12", "title": "JavaScript Basics", "duration": 50 },
        { "date": "2025-03-15", "title": "JavaScript Basics", "duration": 50 },
        { "date": "2025-03-15", "title": "React Guide", "duration": 30 },
        { "date": "2025-03-14", "title": "Node.js Handbook", "duration": 60 },
        { "date": "2025-03-14", "title": "JavaScript Basics", "duration": 20 },
        { "date": "2025-03-11", "title": "JavaScript Basics", "duration": 50 },
        { "date": "2025-03-01", "title": "JavaScript Basics", "duration": 50 },
        { "date": "2025-03-02", "title": "JavaScript Basics", "duration": 50 },
        { "date": "2025-03-03", "title": "JavaScript Basics", "duration": 50 },
        { "date": "2025-03-04", "title": "JavaScript Basics", "duration": 50 },
        { "date": "2025-03-05", "title": "React Guide", "duration": 30 },
        { "date": "2025-03-06", "title": "Node.js Handbook", "duration": 60 },
        { "date": "2025-03-04", "title": "JavaScript Basics", "duration": 20 },
        { "date": "2025-03-07", "title": "JavaScript Basics", "duration": 50 },
        { "date": "2025-03-08", "title": "JavaScript Basics", "duration": 50 },
        { "date": "2025-03-10", "title": "JavaScript Basics", "duration": 50 },
        { "date": "2025-03-12", "title": "JavaScript Basics", "duration": 50 },
        { "date": "2025-03-11", "title": "JavaScript Basics", "duration": 50 },
        { "date": "2025-03-13", "title": "React Guide", "duration": 30 },
        { "date": "2025-03-20", "title": "Node.js Handbook", "duration": 60 },
        { "date": "2025-03-21", "title": "JavaScript Basics", "duration": 20 },

        { "date": "2025-03-28", "title": "Node.js Handbook", "duration": 60 },
        { "date": "2025-03-29", "title": "JavaScript Basics", "duration": 20 },
        { "date": "2024-04-01", "title": "JavaScript Basics", "duration": 50 },
        { "date": "2024-04-02", "title": "JavaScript Basics", "duration": 50 },
        { "date": "2024-04-03", "title": "JavaScript Basics", "duration": 50 },
        { "date": "2024-04-08", "title": "JavaScript Basics", "duration": 50 },
        { "date": "2024-04-15", "title": "JavaScript Basics", "duration": 50 },
        { "date": "2024-04-15", "title": "React Guide", "duration": 30 },
        { "date": "2024-03-14", "title": "Node.js Handbook", "duration": 60 },
        { "date": "2024-04-14", "title": "JavaScript Basics", "duration": 20 },
        { "date": "2024-03-17", "title": "JavaScript Basics", "duration": 50 },

        { "date": "2025-03-15", "title": "JavaScript Basics", "duration": 50 },
        { "date": "2025-03-15", "title": "React Guide", "duration": 30 },
        { "date": "2025-03-14", "title": "Node.js Handbook", "duration": 60 },
        { "date": "2025-03-14", "title": "JavaScript Basics", "duration": 20 },
        { "date": "2025-03-17", "title": "JavaScript Basics", "duration": 50 },
        { "date": "2025-03-18", "title": "JavaScript Basics", "duration": 50 },
        { "date": "2025-03-19", "title": "JavaScript Basics", "duration": 50 },
        { "date": "2025-03-12", "title": "JavaScript Basics", "duration": 50 },
        { "date": "2025-03-15", "title": "JavaScript Basics", "duration": 50 },
        { "date": "2025-03-15", "title": "React Guide", "duration": 30 },
        { "date": "2025-03-14", "title": "Node.js Handbook", "duration": 60 },
        { "date": "2025-03-14", "title": "JavaScript Basics", "duration": 20 },
        { "date": "2025-03-11", "title": "JavaScript Basics", "duration": 50 },
        { "date": "2025-03-01", "title": "JavaScript Basics", "duration": 50 },
        { "date": "2025-03-02", "title": "JavaScript Basics", "duration": 50 },
        { "date": "2025-03-03", "title": "JavaScript Basics", "duration": 50 },
        { "date": "2025-03-04", "title": "JavaScript Basics", "duration": 50 },
        { "date": "2025-03-14", "title": "Node.js Handbook", "duration": 60 },
        { "date": "20253-04-14", "title": "JavaScript Basics", "duration": 20 },
        { "date": "20253-03-17", "title": "JavaScript Basics", "duration": 50 },
        { "date": "20253-03-18", "title": "JavaScript Basics", "duration": 50 },
        { "date": "20253-03-19", "title": "JavaScript Basics", "duration": 50 },
        { "date": "20253-05-12", "title": "JavaScript Basics", "duration": 50 },
        { "date": "20253-06-18", "title": "JavaScript Basics", "duration": 50 },
        { "date": "20253-05-19", "title": "JavaScript Basics", "duration": 50 },
        { "date": "20253-03-23", "title": "JavaScript Basics", "duration": 50 },
        { "date": "20253-03-24", "title": "JavaScript Basics", "duration": 50 },
        { "date": "20253-03-25", "title": "JavaScript Basics", "duration": 50 },
        { "date": "20253-03-26", "title": "JavaScript Basics", "duration": 50 },
        { "date": "20253-03-27", "title": "React Guide", "duration": 30 },
        { "date": "20253-03-28", "title": "Node.js Handbook", "duration": 60 },
        { "date": "20253-03-29", "title": "JavaScript Basics", "duration": 20 },
        { "date": "20243-04-01", "title": "JavaScript Basics", "duration": 50 },
        { "date": "20243-04-02", "title": "JavaScript Basics", "duration": 50 },
        { "date": "20243-04-03", "title": "JavaScript Basics", "duration": 50 },
        { "date": "20243-04-08", "title": "JavaScript Basics", "duration": 50 },
        { "date": "20243-04-15", "title": "JavaScript Basics", "duration": 50 },
        { "date": "20243-04-15", "title": "React Guide", "duration": 30 },
        { "date": "20243-03-14", "title": "Node.js Handbook", "duration": 60 },
        { "date": "20243-04-14", "title": "JavaScript Basics", "duration": 20 },
        { "date": "20243-03-17", "title": "JavaScript Basics", "duration": 50 },
        { "date": "20243-03-18", "title": "JavaScript Basics", "duration": 50 },
        { "date": "2023-03-19", "title": "JavaScript Basics", "duration": 50 },
        { "date": "2023-05-12", "title": "JavaScript Basics", "duration": 50 },
        { "date": "2023-06-18", "title": "JavaScript Basics", "duration": 50 },
        { "date": "2023-05-19", "title": "JavaScript Basics", "duration": 50 },
        { "date": "2023-05-12", "title": "JavaScript Basics", "duration": 50 },
        { "date": "2023-05-12", "title": "JavaScript Basics", "duration": 50 }
    ];

    const transformData = (data: StudyEntry[]): TransformedEntry[] => {
        const groupedData: Record<string, TransformedEntry> = {};

        data.forEach(({ date, title, duration }) => {
            if (!groupedData[date]) {
                groupedData[date] = { date };
            }

            // 确保 title 为空时使用默认 key
            const validTitle = title?.trim() || "Other";

            groupedData[date][validTitle] = (groupedData[date][validTitle] as number || 0) + duration;
        });

        return Object.values(groupedData).sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime());
    };


    // 使用 useEffect 进行数据转换
    useEffect(() => {
        fetchWithAuth("api/auth/My", { action: "init", params: {} })
            .then((res: any) => {
                // console.log(res.data)
                // const transformedData = transformData(ti);
                const transformedData = transformData(res.data);
                console.log("转换后的数据:", transformedData);
                setStudyTime(transformedData);
            });

    }, [currentPath]); // 空依赖数组，组件挂载时运行一次

    // 获取所有 title（用于绘制多条 Bar）
    const allTitles: string[] = [...new Set(studyTime.flatMap(entry => Object.keys(entry).filter(key => key !== "date")))];

    // 预定义颜色列表（用于未定义的 title）
    // 随机生成颜色（HSL 确保颜色均匀分布）
    const generateRandomColor = () => {
        const hue = Math.floor(Math.random() * 360); // 0 - 360 度，代表颜色
        const saturation = 70 + Math.random() * 20; // 70% - 90% 饱和度，保证颜色鲜艳
        const lightness = 50 + Math.random() * 10; // 50% - 60% 亮度，避免颜色太暗或太亮
        return `hsl(${hue}, ${saturation}%, ${lightness}%)`;
    };

    // 获取颜色（如果 title 没有颜色，则分配一个）
    const getColor = (title: string) => {
        if (!colorMap[title]) {
            colorMap[title] = generateRandomColor();
        }
        return colorMap[title];
    };

    const colorMap: Record<string, string> = {
        "Other": "#ff7300"
    };

    return (
        <>
            <div>
                <Mainbar />
            </div>
            <div className="flex flex-col items-center justify-center w-full mx-auto max-w-7xl mx-15 pt-25">
                <div className="rounded-lg flex flex-col items-center justify-center w-full border-2 border-[#0285ff]">
                    <div>
                        <h2>学习时间</h2>
                    </div>
                    <div className="w-full flex justify-end p-1">
                        <div className="overflow-x-auto custom-scrollbar-hide" style={{ direction: "rtl" }}>
                            <ResponsiveContainer width={Math.max(250, Math.min(studyTime.length * 40, 1120))} height={250}>
                                <BarChart
                                    data={studyTime} // 数据
                                    layout="horizontal"  // 横向布局
                                    barGap={0}  // 设置柱子之间的间距为0，保持紧密
                                    barCategoryGap={1}  // 设置不同类别之间的间隙为10px
                                >
                                    <XAxis
                                        type="category" // X 轴为分类轴
                                        dataKey="date" // 使用日期作为分类
                                        tickFormatter={(date) => {
                                            // 确保 date 是字符串
                                            const dateString = typeof date === "string" ? date : new Date(date).toISOString();
                                            return dateString.slice(5); // 只保留 "MM-DD"
                                        }}
                                    />

                                    <Tooltip content={({ payload }) => {
                                        if (!payload || payload.length === 0) return null;
                                        return (
                                            <div style={{
                                                backgroundColor: "white",
                                                padding: "10px",
                                                border: "1px solid #ccc",
                                                borderRadius: "8px",
                                                boxShadow: "0px 4px 10px rgba(0, 0, 0, 0.1)"
                                            }}>
                                                <p>{payload[0].payload.date}</p>
                                                {payload.map((entry, index) => (
                                                    <p key={index} style={{ color: entry.color }}>
                                                        {entry.name}: {entry.value} 分钟
                                                    </p>
                                                ))}
                                            </div>
                                        );
                                    }} />
                                    {allTitles.map((title) => (
                                        <Bar
                                            barSize={10}
                                            key={title}
                                            dataKey={title}
                                            stackId="a"
                                            fill={getColor(title) || "#ff7300"}
                                        // radius={[10, 10, 0, 0]}
                                        />
                                    ))}
                                </BarChart>
                            </ResponsiveContainer>
                        </div>
                    </div>
                </div>


                <div className="rounded-lg flex w-full max-w-7xl border-2 border-[#0285ff] p-1 m-1">
                    <div className="mx-5 flex flex-col items-center" onClick={() => { router.push("/rank") }}>
                        <div className="w-[7rem] h-[10rem] rounded-lg bg-[#ffffff]">
                            <img className="w-full h-full object-cover rounded-lg" src="https://www.diydoutu.com/bq/2157.gif" alt="top" />
                        </div>
                        <span className="block text-ellipsis overflow-hidden whitespace-nowrap w-[7rem] text-center">
                            卷王排行榜
                        </span>
                    </div>
                    <div className="mx-5 flex flex-col items-center" onClick={() => { router.push("/wordCloud") }}>
                        <div className="w-[7rem] h-[10rem] rounded-lg bg-[#ffffff]">
                            <img className="w-full h-full object-cover rounded-lg" src="https://www.diydoutu.com/bq/2157.gif" alt="top" />
                        </div>
                        <span className="block text-ellipsis overflow-hidden whitespace-nowrap w-[7rem] text-center">
                            云词
                        </span>
                    </div>
                </div>
            </div>
        </>
    );
}
